<?php
/**
 * DMFramework
 * 
 * @license Copyright 2012 Dillen Meijboom under the Apache license version 2.0 (http://apache.org/licenses/LICENSE-2.0)
 * @author Dillen Meijboom <info@dillenm.nl>
 * @url http://dmframework.nl
 */

/**
 * The files library
 * 
 * @license Copyright 2012 Dillen Meijboom under the Apache license version 2.0 (http://apache.org/licenses/LICENSE-2.0)
 * @author Dillen Meijboom <info@dillenm.nl>
 * @package System.Library
 */
class Dmf_Files
{
    /**
     * Get file
     * 
     * @param string $filename
     * @return Dmf_File 
     */
    public static function file( $filename )
    {
        $file = new Dmf_File( $filename );
        return $file;
    }
    
    /**
     * Get directory
     * 
     * @param string $filename
     * @return Dmf_Directory 
     */
    public static function dir( $filename )
    {
        $dir = new Dmf_Directory( $filename );
        return $dir;
    }
    
    /**
     * Get a list of File or Directory objects
     * 
     * @param string $dir
     * @return array
     */
    public function getFiles( $dir )
    {
        $list = $this->getList( $dir );
        $files = array();
        
        foreach( $list as $index => $value )
        {
            if ( is_array( $value ) )
            {
                $files[] = new Dmf_Directory( realpath( $dir . '/' . $index ) );
            }
            else
            {
                $files[] = new Dmf_File( $value );
            }
        }
        
        return $files;
    }
    
    /**
     * Get a full list of files.
     * 
     * @param string $dir
     * @param boolean $recursive
     * @return array
     * @throws Exception 
     */
    public function getList( $dir, $recursive = true )
    {
        if ( ! is_dir( $dir ) )
        {
            throw new Exception( 'Directory: "' . $dir . '" not found.' );
        }
        
        if ( ! is_readable( $dir ) )
        {
            return array();
        }
        
        $list = array();
        
        foreach( scandir( $dir ) as $file )
        {
            if ( $file == '.' || $file == '..' ) 
            {
                continue;
            }
            
            $filepath = $dir . '/' . $file;
            
            if ( filetype( $filepath ) == 'dir' )
            {
                if ( $recursive )
                {
                    $list[ $file ] = $this->getList( $filepath );
                }
                else
                {
                    $list[] = realpath( $filepath );
                }
            }
            else
            {
                $list[] = realpath( $filepath );
            }
        }
        
        return $list;
    }
}